﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Nature.Core.Config
{
    public abstract class BaseConfigElementCollection<T>
        : ConfigurationElementCollection
        where T : BaseConfigElement, new()
    {
        protected override string ElementName
        {
            get { return ItemName; }
        }

        protected abstract string ItemName { get; }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        public T this[int index]
        {
            get { return (T)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public new T this[string name]
        {
            get { return this.OfType<T>().Where(p => p.Name == name).FirstOrDefault(); }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new T();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return GetKey((T)element);
        }

        protected virtual object GetKey(T t)
        {
            return t.Name;
        }
    }
}
